package com.hjh.netty.elect.demo4;

import com.hjh.netty.elect.util.NumberDataConvertUtils;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

@Slf4j
public class Pmc350Decoder extends ByteToMessageDecoder {

    private static final int HEADER_SIZE = 7;

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        int length = in.readableBytes();
        if (length < HEADER_SIZE) {
            log.info("decode|length<7|len:{}",length);
            return;
        }
        //固定（F9）开头
        String packetHeader = ByteBufUtil.hexDump(in.readBytes(1)).toUpperCase();
        if (!"F9".equals(packetHeader)) {
            log.info("decode|packetHeader is not F9|packetHeader:{}|len:{}",packetHeader,length);
            return;
        }
        //上传数据
        StringBuilder uploadData = new StringBuilder(packetHeader);
        //包标识
        String packetFlag = ByteBufUtil.hexDump(in.readBytes(1)).toUpperCase();
        uploadData.append(packetFlag);
        //设备识别码长度，这里要+1
        String deviceIdCodeLengthStr = ByteBufUtil.hexDump(in.readBytes(1));
        int diveceIdCodeLength = NumberDataConvertUtils.hexString2decimalInt(deviceIdCodeLengthStr) + 1;
        uploadData.append(deviceIdCodeLengthStr);
        //设备识别码
        String diveceIdCode = ByteBufUtil.hexDump(in.readBytes(diveceIdCodeLength)).toUpperCase();
        uploadData.append(diveceIdCode);
        //PayLoad 部分总长度
        String payLoadLengthStr = ByteBufUtil.hexDump(in.readBytes(1));
        int payLoadLength = NumberDataConvertUtils.hexString2decimalInt(payLoadLengthStr);
        ;
        uploadData.append(payLoadLengthStr);
        //PayLoad 校验和
        String payLoadVerifyTotal = ByteBufUtil.hexDump(in.readBytes(1)).toUpperCase();
        uploadData.append(payLoadVerifyTotal);
        //固定（F9）
        String packetHeaderEnd = ByteBufUtil.hexDump(in.readBytes(1)).toUpperCase();
        uploadData.append(packetHeaderEnd);
        //判断长度是否相等
        if (in.readableBytes() < payLoadLength) {
            return;
        }
        String payLoad = "";
        if (payLoadLength > 0) {
            payLoad = ByteBufUtil.hexDump(in.readBytes(payLoadLength)).toUpperCase();
        }
        uploadData.append(payLoad);
        Pmc350ProtocolModel protocolBean = new Pmc350ProtocolModel(packetHeader, packetFlag, diveceIdCodeLength,
                diveceIdCode, payLoadLength, payLoadVerifyTotal, packetHeaderEnd, payLoad, uploadData.toString());

        out.add(protocolBean);

    }

}
